﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using snat.proxy;
using snat.proxy.items.exceptions;

namespace snat.proxy.items {
    public class Entity : Item, IComparable {

        object nameLock = new object();

        private string name;
        public string Name {
            get {
                lock (nameLock) {
                    if (name == null) {
                        Instantiate();
                    }
                }
                return name;
            }
        }

        private int id;
        public int ID {
            get {
                return id;
            }
        }

        public Entity(DataRow _row, string _entityIDFieldName, string _entityNameFieldName)
            : this(_row.Field<int>(_entityIDFieldName)){

                    this.name = _row.Field<string>(_entityNameFieldName);
    
        }

        public Entity(DataRow _row, params DataSet[] _auxilliary)
            : this(_row.Field<int>("EntityID")) {

                    this.name = _row.Field<string>("EntityName");

        }

        public Entity(int _entityId, string _name = null) {
            this.id = _entityId;
            this.name = _name;
        }

        public override string ToString() {
            return String.Join(" ", "Name:", Name);
        }

        public virtual int CompareTo(object obj) {
            return ID.CompareTo((obj as Entity).ID);
        }

        private void Instantiate() {
            DataSet nameSet = DataProxy.Instance.RunQuery(
                 @"SELECT EntityName FROM Entity
                             WHERE EntityID = " + ID);
            try
            {
                name = nameSet.Tables["Table"].Rows[0].Field<string>("EntityName");
            }
            catch (IndexOutOfRangeException ex)
            {
                throw ex;
     
            }
        }

    }
}
